import { commonBTWifi, commonRestDevice, commonSoftAP } from "./contants";
// eslint-disable-next-line no-unused-vars
import { getConfigsSupportConfigNetwork, IProduct, networkConfigTypes } from "./product";

import categoryJSON from "./category_ext.json";

interface IObj {
  [key: string]: any;
}

/**
 * 修正多语言空字符串问题
 */
export const correctLanguageEmptyString = (language: any) => {
  return Object.entries(language).reduce(
    (lang, [key, value]) => ({
      ...lang,
      [key]: value === "" ? " " : value,
    }),
    {}
  );
};

interface ILanguage {
  [key: string]: IObj;
}

/**
 * 合并多语言
 */
export function mergeLanguage(obj: ILanguage, target: ILanguage) {
  return Object.entries(target).reduce((newObj, [key, value]) => {
    return {
      ...newObj,
      [key]: { ...(newObj[key] || {}), ...value },
    };
  }, obj);
}

/**
 * 是否是有效的配网配置
 */
export function isValidConfig(config: IObj | undefined) {
  return !!(config && config.content && config.content.length > 0);
}

/**
 * 修正产品配置项
 */
export const correctProduct = (
  product: IProduct,
  supportLanguages: { key: string }[]
) => {
  const { productKey } = product;
  // 兼容语言
  let language = { ...product.language } || { zh: {} };
  language.en = { ...language.zh, ...(language.en || {}) }; // 这里有点奇怪了，默认是中文，但是在语言包默认是英文
  supportLanguages.forEach((languageItem) => {
    language[languageItem.key] = {
      ...language.zh,
      ...(language[languageItem.key] || {}),
    };
  });

  // 翻译插件有一个问题，如果文案是空，就会报错
  language = Object.entries(language).reduce(
    (lang, [key, value]) => ({
      ...lang,
      [key]: correctLanguageEmptyString(value),
    }),
    {}
  );

  // 默认的配置文件
  const defaultConfig = {
    networkConfigType: [],
    m2mProtoc: 'WIFI',
    isGatewayProduct: false,
    isGatewaySubdeviceProduct: false,
    isCenterControlProduct: false,
    icon: `./static/${productKey}/device_icon.png`,
    softAPPassword: "",
  };

  const deviceConfigKeys: (keyof IProduct)[] = [
    "airLink",
    "softAp",
    "btWifi",
    "resetDevice",
  ];
  const commonConfig = {
    airLink: {},
    softAp: commonSoftAP,
    btWifi: commonBTWifi,
    resetDevice: commonRestDevice,
  };

  // 补充配网配置，如airLink, softAp, btWifi, resetDevice
  const deviceConfig = deviceConfigKeys.reduce(
    (config, key) => ({
      ...config,
      [key]: isValidConfig(product[key]) // 如果是有效配网配置，则使用本身，否则使用默认配置
        ? product[key]
        : {
            content:
              commonConfig[
                key as "airLink" | "softAp" | "btWifi" | "resetDevice"
              ].content,
          },
    }),
    {}
  );

  // 补充配网配置的多语言
  language = deviceConfigKeys.reduce((lang, key) => {
    if (isValidConfig(product[key])) {
      return lang;
    }
    return mergeLanguage(
      lang,
      commonConfig[key as "airLink" | "softAp" | "btWifi" | "resetDevice"]
        .language || {}
    );
  }, language);

  return {
    ...defaultConfig,
    ...product,
    ...deviceConfig,
    language,
  };
};

/**
 * 修正产品配置
 */
export const correctProducts = (
  products: any[],
  supportLanguages: { key: string }[]
) => {
  /**
   * 计算配置文件
   */
  return products.map((item) => correctProduct(item, supportLanguages));
};

export function getProductLanguageJson(product: IProduct, languageKey: string) {
  return (
    product.language[languageKey] ||
    product.language[languageKey.slice(0, 2)] ||
    product.language.en ||
    {}
  );
}

export interface ICategory {
  id: number;
  name: string;
  icon: string;
  protoc_types: string[];
  parent_id: number;
  is_customize: boolean;
  level: number;
  children: ICategory[];
  productKey?: string;
  gid?: string;
}

const sortData = (data: ICategory[]) => {
  data.sort((a, b) => b.level - a.level);
  data.map((item) => {
    if (item.children) {
      item.children = sortData(item.children);
    }
  });
  return data;
};

const getLeverData = (nodes: ICategory[]) => {
  function cmp(a, b) {
    return a.parent_id - b.parent_id;
  }
  nodes.sort(cmp);

  const midObj = {};
  // 从后向前遍历
  for (let i = nodes.length - 1; i >= 0; i--) {
    const nowPid = nodes[i].parent_id || 0;
    const nowId = nodes[i].id;
    // 建立当前节点的父节点的children 数组
    if (midObj[nowPid]) {
      midObj[nowPid].push(nodes[i]);
    } else {
      midObj[nowPid] = [];
      midObj[nowPid].push(nodes[i]);
    }
    // 将children 放入合适的位置
    if (midObj[nowId]) {
      nodes[i].children = midObj[nowId];
      delete midObj[nowId];
    }
  }

  return midObj[0];
};

let categoryList: ICategory[] = [];

export function initCategory() {
  if (!categoryList || categoryList.length < 1) {
    categoryList = sortData(getLeverData(categoryJSON.data as ICategory[]));
  }
  console.log("categoryList", categoryList);
  return categoryList;
}

// 固定生产一个假的产品配置
export function getFakeProduct(p: ICategory) {
  const product = getConfigsSupportConfigNetwork()[0];
  // console.log('product', p);
  let m2mProtoc;
  if (p.protoc_types && p.protoc_types.length > 0) {
    m2mProtoc = p.protoc_types[0].toUpperCase();
  } else {
    m2mProtoc = 'WIFI';
  }
  Object.assign(product, {
    name: p.name,
    icon: p.icon,
    m2mProtoc,
    networkConfigType: [networkConfigTypes.TNetworkConfigTypeBTWifi, networkConfigTypes.TNetworkConfigTypeSoftAp],
    wxTemplateId: "com.gizwits.wx.ai",
  });
  product.language.zh.PL_PRODUCT_NAME = p.name;
  delete product.btWifi;
  delete product.softAp;
  delete product.resetDevice;
  return product;
}
